package com.whfc.emp.service.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.common.enums.ApprovalResult;
import com.whfc.common.result.PageData;
import com.whfc.common.util.NumberParser;
import com.whfc.common.util.PageUtil;
import com.whfc.emp.dao.*;
import com.whfc.emp.dto.AppAttachDTO;
import com.whfc.emp.dto.AppEmpDTO;
import com.whfc.emp.entity.AppEmp;
import com.whfc.emp.entity.AppEntryApplication;
import com.whfc.emp.service.AppEmpService;
import com.whfc.emp.service.AppEntryApplicationService;
import com.whfc.entity.dto.Apply.rep.EntryApplicationListRep;
import com.whfc.entity.dto.Apply.rep.QueryEmpSysIdDto;
import com.whfc.entity.dto.Apply.rep.QueryIdNameRep;
import com.whfc.entity.dto.Apply.req.*;
import com.whfc.fuum.entity.SysEmpUser;
import com.whfc.fuum.entity.SysUser;
import com.whfc.fuum.entity.WxUser;
import com.whfc.fuum.service.SysDeptService;
import com.whfc.fuum.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 人员申请
 *
 * @author xie_jiangyong
 * @version 1.0
 * @date 2025/9/13 10:34
 */
@DubboService(interfaceClass = AppEntryApplicationService.class, version = "1.0.0", timeout = 30 * 1000)
public class AppEntryApplicationServiceImpl implements AppEntryApplicationService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AppEntryApplicationMapper appEntryApplicationMapper;

    @Autowired
    private AppEmpMapper appEmpMapper;

    @Autowired
    private AppEmpContractMapper appEmpContractMapper;

    @Autowired
    private AppEmpCertMapper appEmpCertMapper;

    @Autowired
    private AppEmpHealthReportMapper appEmpHealthReportMapper;

    @DubboReference(interfaceClass = AppEmpService.class, version = "1.0.0", timeout = 30000)
    private AppEmpService appEmpService;

    @DubboReference(interfaceClass = SysUserService.class, version = "1.0.0", timeout = 30000)
    private SysUserService sysUserService;
    @DubboReference(interfaceClass = SysDeptService.class, version = "1.0.0")
    private SysDeptService sysDeptService;

    @Override
    public PageData<EntryApplicationListRep> getAppEntryList(SysUser user,AppEntryApplicationReq req) {

        // 查询项目下的个个机构管理人员
//        List<UserDeptDTO> messageList = sysDeptService.queryMessage(req.getDeptId());
//        List<Integer> userIdList = new ArrayList<>();
//        if (messageList != null && !messageList.isEmpty()) {
//            userIdList = messageList.stream()
//                    .map(UserDeptDTO::getUserId)
//                    .filter(Objects::nonNull)
//                    .collect(Collectors.toList());
//        }
//        userIdList.add(user.getId());
//        req.setCreateUserId(userIdList);
        // 获取机构
        String integers = sysDeptService.selectDeptIdById(user.getId());
        List<Integer> pidList = NumberParser.parseCommaSeparatedNumbers(integers);
        req.setPidList(pidList);
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<AppEntryApplication> listReps = appEntryApplicationMapper.getAppEntryList(pidList, req.getUserId(), req.getEntryTimeBegin(), req.getEntryTimeEnd(),
                req.getLeaveTimeBegin(), req.getLeaveTimeEnd(), req.getAuditStatus());

        if (CollectionUtils.isEmpty(listReps)) {
            return PageUtil.pageData(new PageInfo<>());
        }

        Page<AppEntryApplication> originalPage = (Page<AppEntryApplication>) listReps;

        List<EntryApplicationListRep> entryApplicationListReps = new ArrayList<>();
        for (AppEntryApplication application : listReps) {
            EntryApplicationListRep en = new EntryApplicationListRep();
            en.setName("未知用户");
            en.setIdCard("");
            en.setUnit("未知单位");

            // 查询创建人信息
            List<QueryEmpSysIdDto> appEmpIds = sysUserService.getAppEmpEmpNamesIdList(Arrays.asList(application.getCreateUser()));
            if (!CollectionUtils.isEmpty(appEmpIds)) {
                AppEmpDTO empInfo = appEmpService.getEmpInfo(appEmpIds.get(0).getAppEmpId());
                en.setName(empInfo.getEmpName());
                en.setIdCard(empInfo.getIdCardNo());
                en.setUnit(empInfo.getCorpName());
            }

            // 查询入场人员
            List<String> personId = new  ArrayList<>();
            if(application.getEntryPersonId().contains("/")){
                personId = Arrays.asList(application.getEntryPersonId().split("/"));
            }else {
                personId = Arrays.asList(application.getEntryPersonId());
            }
            Arrays.asList(application.getEntryPersonId().split("/"));
            List<String> personNmae = new ArrayList<>();
            List<QueryEmpSysIdDto> personIds = sysUserService.getAppEmpEmpNamesIdList(personId);
            for (QueryEmpSysIdDto queryEmpSysIdDto : personIds) {
                AppEmpDTO empInfo = appEmpService.getEmpInfo(queryEmpSysIdDto.getAppEmpId());
                personNmae.add(empInfo.getEmpName());
            }

            en.setId(application.getId());
            en.setEntryTime(application.getEntryTime());
            en.setLeaveTime(application.getLeaveTime());
            en.setUploadedFile(application.getFilePath());
            en.setReason(application.getReason());
            en.setApplyTime(application.getCreateTime());
            en.setApprovalStatus(application.getApprovalStatus());
            en.setEntryPersonNames(personNmae);
            entryApplicationListReps.add(en);
        }
        entryApplicationListReps = entryApplicationListReps.stream()
                .sorted(Comparator.comparing(EntryApplicationListRep::getId).reversed())
                .collect(Collectors.toList());
//        PageInfo<EntryApplicationListRep> voPageInfo = new PageInfo<>(entryApplicationListReps);
//        voPageInfo.setTotal(originalPage.getTotal());
//        voPageInfo.setPages(originalPage.getPages());
//        voPageInfo.setPageNum(originalPage.getPageNum());
//        voPageInfo.setPageSize(originalPage.getPageSize());
//        return PageUtil.pageData(voPageInfo);
        // 创建新的分页对象，保持原始分页信息
        Page<EntryApplicationListRep> resultPage = new Page<>(originalPage.getPageNum(), originalPage.getPageSize());
        resultPage.setTotal(originalPage.getTotal());
        resultPage.addAll(entryApplicationListReps);

        PageInfo<EntryApplicationListRep> voPageInfo = new PageInfo<>(resultPage);
        return PageUtil.pageData(voPageInfo);
    }

    @Override
    public void edit(AppUpEntryApplicationDTO req) {
        AppEntryApplication app = new  AppEntryApplication();
        app.setId(req.getId()); // 主键
        String entryPersonId = req.getEntryPersonIds() == null && req.getEntryPersonIds().size() > 0 ? "" : String.join("/", req.getEntryPersonIds());
        app.setEntryPersonId(entryPersonId); // 人员
        app.setTeamLeaderId(req.getTeamLeaderId()); // 班组长
        app.setEntryTime(req.getEntryTime());// 入场时间
        app.setLeaveTime(req.getLeaveTime()); // 离场时间
        app.setSubcontractorId(req.getSubcontractorId()); // 分包单位Id
        app.setGeneralContractorId(req.getGeneralContractorId()); // 总包单位Id
        app.setSupervisionUnitId(req.getSupervisionUnitId()); // 监理单位
        app.setOwnerUnit(req.getOwnerUnit()); // 业主单位Id
        app.setFilePath(req.getFilePath()); // 文件路径
        app.setReason(req.getReason()); // 申请理由
        app.setCreateUser(req.getCreateUser()); // 申请人
        appEntryApplicationMapper.updateByPrimaryKey(app);
    }

    /**
     * 根据创建人查询入场申请
     * @param createUserId
     * @return
     */
    @Override
    public List<AppEntryApplication> selectByCreateUser(String createUserId) {
        return appEntryApplicationMapper.selectByCreateUser(createUserId);
    }

    @Override
    public PageData<AppEntryApplication> selectByTimeAndStatus(List<Integer> pidList, Integer createUserId, LocalDateTime entryTimeBegin, LocalDateTime entryTimeEnd, LocalDateTime leaveTimeBegin, LocalDateTime leaveTimeEnd, Integer approvalStatus, Integer pageNum, Integer pageSize) {
        // 启用PageHelper分页
        PageHelper.startPage(pageNum, pageSize);

        // 执行查询，PageHelper会自动拦截并添加分页逻辑
        List<AppEntryApplication> resultList = appEntryApplicationMapper.selectByTimeAndStatus(pidList, createUserId, entryTimeBegin, entryTimeEnd, leaveTimeBegin, leaveTimeEnd, approvalStatus);

        // 获取分页信息
        PageInfo<AppEntryApplication> pageInfo = new PageInfo<>(resultList);

        // 打印调试信息
        logger.info("分页查询 - PageNum: {}, PageSize: {}, Total: {}, ResultSize: {}",
                pageNum, pageSize, pageInfo.getTotal(), resultList.size());

        // 返回分页数据
        return PageUtil.pageData(pageInfo);
    }

    @Override
    public AppEntryApplicationDTO saveApply(Integer id, AppEntryApplicationDTO appEntryApplication) {
        AppEntryApplication app = new  AppEntryApplication();
        List<String> entryPersonIds = appEntryApplication.getEntryPersonIds();
        String entryPersonId = entryPersonIds == null ? "" : String.join("/", entryPersonIds);
        if (appEntryApplication.getId() == null){
            BeanUtils.copyProperties(appEntryApplication, app);
            app.setEntryPersonId(entryPersonId);
            app.setCreateUser(String.valueOf(id));
            app.setApprovalStatus(ApprovalResult.PENDING.getValue());
            appEntryApplicationMapper.insert(app);
        }else {
            app = appEntryApplicationMapper.selectByPrimaryKey(appEntryApplication.getId());
            if (app != null){
                BeanUtils.copyProperties(appEntryApplication, app);
                app.setEntryPersonId(entryPersonId);
                appEntryApplicationMapper.updateByPrimaryKey(app);
            }
        }

        appEntryApplication.setId(app.getId());
        return appEntryApplication;
    }

    @Override
    public List<SafetyTrainingExamReq> queryPersonnel(QueryPersonnelReq req) {
        // 查询原始数据并快速返回空结果
        List<AppEmpDTO> appEmpDTOS = new ArrayList<>();
        if(req.getEmpNames() != null && req.getEmpNames().size() > 0){
            for (String empName : req.getEmpNames()) {
                appEmpMapper.selectByDeptIdApp(req.getLeaderFlag(), empName);
                appEmpDTOS.addAll(appEmpMapper.selectByDeptIdApp(req.getLeaderFlag(), empName));
            }
        }else {
            appEmpDTOS.addAll(appEmpMapper.selectByDeptIdApp(req.getLeaderFlag(), null));
        }

        if (CollectionUtils.isEmpty(appEmpDTOS)) {
            return Collections.emptyList();
        }

        return appEmpDTOS.stream()
                .map(this::convertToExamReq)
                .collect(Collectors.toList());
    }

    @Override
    public List<UserDeptDTO> queryMessage(String phone) {

        return Collections.emptyList();
    }

    @Override
    public int updateApprovalResult(AppEntryApplication application) {
        int i = appEntryApplicationMapper.updateByPrimaryKey(application);
        return i;
    }

    @Override
    public List<AppEntryApplication> selectByCreator(Integer userId) {
        return appEntryApplicationMapper.selectByCreator(userId);
    }

    @Override
    public AppEntryApplication selectByPrimaryKey(Integer id) {
        return appEntryApplicationMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<SafetyTrainingExamReq> getEntryPerson(List<Integer> entryPersonId) {
        List<AppEmpDTO> appEmpDTOS = appEmpMapper.selectByPrimaryKeyList(entryPersonId);
        if(!CollectionUtils.isEmpty(appEmpDTOS)){
            return Collections.emptyList();
        }
        return appEmpDTOS.stream()
                .map(this::convertToExamReq)
                .collect(Collectors.toList());
    }

    @Override
    public List<QueryIdNameRep> getIdName(List<Integer> entryPersonId) {
        List<QueryIdNameRep> idName = appEmpMapper.getIdName(entryPersonId);
        if(!CollectionUtils.isEmpty(idName)){
            return Collections.emptyList();
        }
        return idName;
    }


    /**
     * 将AppEmpDTO转换为SafetyTrainingExamReq
     */
    private SafetyTrainingExamReq convertToExamReq(AppEmpDTO empDTO) {
        SafetyTrainingExamReq req = new SafetyTrainingExamReq();

        // 基础信息映射
        req.setEmp_id(empDTO.getEmpId());
        req.setName(empDTO.getEmpName());
        req.setGender(convertGender(empDTO.getGender()));
        req.setCompany(empDTO.getCorpName());
        req.setPosition(empDTO.getWorkTypeName());
        req.setAddress(empDTO.getAddress());
        req.setHardwareNumber(empDTO.getSn());
        req.setExamStatus("未考试");

        // 合同信息（复用转换方法）
        List<AppAttachDTO> contractDTOs = appEmpContractMapper.selectByEmpIdUrl(empDTO.getEmpId());
        req.setContractFileName(convertAttachList(contractDTOs));

        // 资质证书信息
        List<AppAttachDTO> certDTOs = appEmpCertMapper.selectByEmpIdUrl(empDTO.getEmpId());
        req.setQualificationCertificateNmae(convertAttachList(certDTOs));

        // 体检报告（类型1）
        List<AppAttachDTO> healthReportDTOs = appEmpHealthReportMapper.selectByEmpIdImg(empDTO.getEmpId(), "1");
        req.setMedicalReportNmae(convertAttachList(healthReportDTOs));

        // 社保证明（类型2）
        List<AppAttachDTO> insuranceDTOs = appEmpHealthReportMapper.selectByEmpIdImg(empDTO.getEmpId(), "2");
        req.setSocialSecurityProofNmae(convertAttachList(insuranceDTOs));

        return req;
    }

    /**
     * 通用转换方法：将List<AppAttachDTO>转为List<Map<String, String>>
     * 复用逻辑，减少代码冗余
     */
    private List<Map<String, String>> convertAttachList(List<AppAttachDTO> attachList) {
        // 空集合直接返回空列表，避免后续流处理空指针
        if (CollectionUtils.isEmpty(attachList)) {
            return Collections.emptyList();
        }

        return attachList.stream()
                .filter(Objects::nonNull)
                .filter(dto ->
                        // 统一过滤条件：name和url非空且非空白
                        dto.getName() != null && !dto.getName().trim().isEmpty() &&
                                dto.getUrl() != null && !dto.getUrl().trim().isEmpty()
                )
                .map(dto -> {
                    Map<String, String> map = new HashMap<>(2);
                    map.put("name", dto.getName().trim());
                    map.put("url", dto.getUrl().trim());
                    return map;
                })
                .collect(Collectors.toList());
    }

    /**
     * 性别转换工具方法
     */
    private String convertGender(Integer gender) {
        return gender == null ? "未知" :
                gender == 1 ? "男" :
                        gender == 2 ? "女" : "未知";
    }

}
